package com.example.shellshopping.login;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shellshopping.R;
import com.example.shellshopping.personCenter.PersonCenterSettingActivity;
import com.example.shellshopping.utils.BaseActivity;
import com.example.shellshopping.utils.ChangeHeadDialog;
import com.example.shellshopping.utils.SaveUserUtils;
import com.example.shellshopping.utils.URLUtils;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
/* 个人中心 */

public class PersonCenterMainActivity extends BaseActivity {

    TextView telTV, nickNameTV, nameTV, addressTV;
    ImageView nickNameIV, nameIV, addressIV,backIV,headIv;
    EditText input_ET;
    TextView saveTV,headTv;
    RadioButton settingGB;


    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //String nickname = nickNameTV.getText().toString();
            //String name = nameTV.getText().toString();
            //String address = addressTV.getText().toString();

            boolean flag = isSamObj();
            if (!flag) {  //可以执行网络请求
                Map<String, String> map = new HashMap<>();
                map.put("id", String.valueOf(userInfo.getId()));
                map.put("name", newUserInfo.getName());
                map.put("address", newUserInfo.getAddress());
                map.put("nickname", newUserInfo.getNickname());
                postNetwork(URLUtils.updateInfo_url, map);
            }else Toast.makeText(PersonCenterMainActivity.this,"已保存最新数据",Toast.LENGTH_SHORT).show();
        }
    };

    //@RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private boolean isSamObj() {
        String nn = nickNameTV.getText().toString().trim();
        String ad = addressTV.getText().toString().trim();
        String name = nameTV.getText().toString().trim();
        newUserInfo.setAddress(ad);
        newUserInfo.setNickname(nn);
        newUserInfo.setName(name);
        return newUserInfo.equals(userInfo);
        //return true;
    }

    @Override
    public void onSuccess(String result) {
        super.onSuccess(result);
        //解析数据
        UserBean bean = new Gson().fromJson(result, UserBean.class);
        //
        int code = bean.getCode();
        switch (code) {
            case 200:  //修改成功
                SaveUserUtils.saveUserToFile(this,newUserInfo);
                userInfo = SaveUserUtils.getUserInfo(this);
                Toast.makeText(this, "修改成功！", Toast.LENGTH_SHORT).show();
                break;
            case 201:  //修改失败
                Toast.makeText(this, "修改失败！", Toast.LENGTH_SHORT).show();
                break;
            default:   //其他，修改失败
                Toast.makeText(this, "其他，修改失败！", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private UserBean.DataBean userInfo; //之前登录时保存的用户信息
    UserBean.DataBean newUserInfo;
    String imgpath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_center_main);
        userInfo = SaveUserUtils.getUserInfo(this);
        newUserInfo = new UserBean.DataBean(userInfo.getId(),userInfo.getPhone(),userInfo.getPassword(),
                userInfo.getName(),userInfo.getAddress(),userInfo.getNickname(),userInfo.getQuestion(),
                userInfo.getAnswer());
        //保存文件的路径
        imgpath = URLUtils.getImgPath(this,userInfo.getPhone());

        initView();
        setListener();  //设置监听事件
        putLoginMessage();  //将登录信息输出到个人用户界面
    }

    //设置监听事件
    private void setListener() {
        nickNameIV.setOnClickListener(onClickListener);
        nameIV.setOnClickListener(onClickListener);
        addressIV.setOnClickListener(onClickListener);
        backIV.setOnClickListener(onClickListener);
        settingGB.setOnClickListener(onClickListener);
        headIv.setOnClickListener(onClickListener);
        headTv.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener= new View.OnClickListener(){
        @Override
        public void onClick(View v){
            int id = v.getId();
            switch(id){
                case R.id.center_iv_nickname:
                    changeNickname();
                    break;
                case R.id.center_iv_name:
                    changeName();
                    break;
                case R.id.center_iv_address:
                    changeAddress();
                    break;
                case R.id.center_iv_back:
                    backLastFra();
                    break;
                case R.id.center_rb2:
                    jumpToSettings();
                    break;
                case R.id.center_tv_head:
                    showChangeheadDialog();
                    break;
                case R.id.center_tv_changeHead:
                    showChangeheadDialog();
                    break;
            }
        }
    };

    //显示对话框
    private void showChangeheadDialog(){
        ChangeHeadDialog headDialog = new ChangeHeadDialog(this);
        headDialog.show();
        headDialog.setDialogWidth();
        headDialog.setOnChangeheadListener(new ChangeHeadDialog.OnChangeheadListener() {
            @Override
            public void clickCamear() {  //跳转到照相机页面
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent,100);
            }

            @Override
            public void clickLocal() {  //跳转到本地图片页面
                Intent intent = new Intent(PersonCenterMainActivity.this,LocalImagActivity.class);
                startActivityForResult(intent,100);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 100) {
            Bundle bundle = data.getExtras();
            Bitmap bm = (Bitmap)bundle.get("data");
            headIv.setImageBitmap(bm);
            saveBitmap(bm);
        }

        if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
            String fpath = data.getStringExtra("fpath");
            Bitmap bitmap = BitmapFactory.decodeFile(fpath);
            headIv.setImageBitmap(bitmap);
            saveBitmap(bitmap);
        }
    }

    //将图片保存起来
    protected void saveBitmap(Bitmap bm){
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(imgpath);
            bm.compress(Bitmap.CompressFormat.JPEG,80,fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void jumpToSettings() {
        Intent intent = new Intent(this, PersonCenterSettingActivity.class);
        startActivity(intent);
    }

    private void backLastFra() {
        if(isSamObj())
        this.finish();
        else{
            showBackDialog();
        }
    }

    //弹出返回对话框
    private void showBackDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息");
        builder.setMessage("当前页面数据有改变，且未保存，是否仍要返回上一级页面");
        builder.setIcon(R.mipmap.icon);
        builder.setPositiveButton("取消",null);
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.create().show();
    }

    private void changeAddress() {
        popDialog(2);
    }

    private void changeName() {
        popDialog(1);
    }

    private void changeNickname() {
        popDialog(0);
    }

    //点击铅笔弹出对话框的设置
    Dialog dialog;
    //弹出对话框
    private void popDialog(int flag) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View myview = inflater.inflate(R.layout.person_center_pop_dialog, null);//引用自定义布局
        input_ET = myview.findViewById(R.id.person_center_inputET);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(myview);
        dialog = builder.create();//创建对话框
        dialog.show();//显示对话框
        switch (flag) {
            case 0:
                myview.findViewById(R.id.person_center_cancel).setOnClickListener(new View.OnClickListener() {//获取布局里面按钮
                    @Override
                    public void onClick(View v) {
                        //String str = inputET.getText().toString();
                        //addressTV.setText("str");
                        dialog.dismiss();//点击按钮对话框消失
                        //Toast.makeText( Main2Activity.this, "点击了残忍离开", Toast.LENGTH_SHORT ).show();
                    }
                });

                myview.findViewById(R.id.person_center_ensure).setOnClickListener(new View.OnClickListener() {//获取布局里面按钮
                    @Override
                    public void onClick(View v) {

                        //String str = input_ET.getText().toString();
                        String str = input_ET.getText().toString();
                        //nickNameTV.setText(str);
                        nickNameTV.setText(str);
                        dialog.dismiss();  //点击按钮对话框消失
                        //Toast.makeText( Main2Activity.this, "点击了残忍离开", Toast.LENGTH_SHORT ).show();
                    }
                });
                break;
            case 1:
                myview.findViewById(R.id.person_center_cancel).setOnClickListener(new View.OnClickListener() {//获取布局里面按钮
                    @Override
                    public void onClick(View v) {
                        //String str = inputET.getText().toString();
                        //addressTV.setText("str");
                        dialog.dismiss();//点击按钮对话框消失
                        //Toast.makeText( Main2Activity.this, "点击了残忍离开", Toast.LENGTH_SHORT ).show();
                    }
                });

                myview.findViewById(R.id.person_center_ensure).setOnClickListener(new View.OnClickListener() {//获取布局里面按钮
                    @Override
                    public void onClick(View v) {

                        //String str = input_ET.getText().toString();
                        String str = input_ET.getText().toString();
                        //nickNameTV.setText(str);
                        nameTV.setText(str);
                        dialog.dismiss();  //点击按钮对话框消失
                        //Toast.makeText( Main2Activity.this, "点击了残忍离开", Toast.LENGTH_SHORT ).show();
                    }
                });
                break;
            case 2:
                myview.findViewById(R.id.person_center_cancel).setOnClickListener(new View.OnClickListener() {//获取布局里面按钮
                    @Override
                    public void onClick(View v) {
                        //String str = inputET.getText().toString();
                        //addressTV.setText("str");
                        dialog.dismiss();//点击按钮对话框消失
                        //Toast.makeText( Main2Activity.this, "点击了残忍离开", Toast.LENGTH_SHORT ).show();
                    }
                });

                myview.findViewById(R.id.person_center_ensure).setOnClickListener(new View.OnClickListener() {//获取布局里面按钮
                    @Override
                    public void onClick(View v) {

                        //String str = input_ET.getText().toString();
                        String str = input_ET.getText().toString();
                        //nickNameTV.setText(str);
                        addressTV.setText(str);
                        dialog.dismiss();  //点击按钮对话框消失
                        //Toast.makeText( Main2Activity.this, "点击了残忍离开", Toast.LENGTH_SHORT ).show();
                    }
                });
                break;
        }

    }



    //将登录信息输出到个人用户界面
    private void putLoginMessage() {
        telTV.setText(userInfo.getPhone());
        nickNameTV.setText(userInfo.getNickname());
        nameTV.setText(userInfo.getName());
        addressTV.setText(userInfo.getAddress());
        File file = new File(imgpath);
        if (file.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(imgpath);
            headIv.setImageBitmap(bitmap);
        }else{
            headIv.setImageResource(R.mipmap.icon);
        }
    }

    private void initView() {
        telTV = findViewById(R.id.center_tv_tel);
        nickNameTV = findViewById(R.id.center_tv_nickname);
        nameTV = findViewById(R.id.center_tv_name);
        addressTV = findViewById(R.id.center_tv_address);
        headIv = findViewById(R.id.center_tv_head);
        headTv = findViewById(R.id.center_tv_changeHead);

        nickNameIV = findViewById(R.id.center_iv_nickname);
        nameIV = findViewById(R.id.center_iv_name);
        addressIV = findViewById(R.id.center_iv_address);
        saveTV = findViewById(R.id.center_tv_save);
        saveTV.setOnClickListener(listener);

        backIV = findViewById(R.id.center_iv_back);
        settingGB = findViewById(R.id.center_rb2);
        //input_ET = findViewById(R.id.person_center_inputET);

        //View view = inflater.inflate(R.layout.fragment_login, container, false);
        //btn1 = findViewById(R.id.person_center_cancel);
        //btn2 = findViewById(R.id.person_center_ensure);
        //btn2.setOnClickListener(listener);
    }
    /*View.OnClickListener listener = new View.OnClickListener(){
        @Override
        public void onClick(View v){

        }
    };*/
}